package com.lxz.bookmanager.service.impl;

import com.lxz.bookmanager.entity.Borrow;
import com.lxz.bookmanager.entity.Reader;
import com.lxz.bookmanager.entity.Record;
import com.lxz.bookmanager.mapper.BorrowMapper;
import com.lxz.bookmanager.mapper.ReaderMapper;
import com.lxz.bookmanager.mapper.RecordMapper;
import com.lxz.bookmanager.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private ReaderMapper readerMapper;

    @Autowired
    private RecordMapper recordMapper;

    @Override
    public void applyBorrowBook(Borrow borrow) {
        borrowMapper.insert(borrow);
    }

    @Override
    public void applyBorrowBooks(Long bookid, String bookname, String borrowusername, int borrowreaderid) {
        borrowMapper.applyBorrowBooks(bookid, bookname, borrowusername, borrowreaderid);
    }

    @Override
    public int applyReaderId(String username) {
        Map<String, Object> map = new HashMap<>();
        map.put("reader_id", username);
        List<Reader> readers = readerMapper.selectByMap(map);
        return readers.get(0).getReaderId();

    }

    @Override
    public String applyReaderName(String username) {
        Map<String, Object> map = new HashMap<>();
        map.put("reader_id", username);
        List<Reader> readers = readerMapper.selectByMap(map);
        return readers.get(0).getName();
    }

    @Override
    public List<Borrow> getAllBorrow() {
        return borrowMapper.selectList(null);
    }

    @Override
    public void acceptBorrow(int sernum) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("sernum", sernum);
        Borrow borrow = borrowMapper.selectByMap(map).get(0);
        Record record = new Record();
        record.setSernum(sernum);
        record.setBookId(borrow.getBookid());
        record.setBookName(borrow.getBookname());
        record.setReaderId(borrow.getBorrowreaderid());
        Calendar calendar = Calendar.getInstance();
        record.setLendDate(calendar.getTime());
        record.setBackState(0);
        recordMapper.insert(record);
        borrowMapper.deleteByMap(map);
    }

    public void ins(Borrow borrow) {

    }
}
